import { resolve } from "path";
import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import vitePluginEslint from "vite-plugin-eslint";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import viteCompression from "vite-plugin-compression";
import { VantResolver } from "@vant/auto-import-resolver";
import pxToVw from "postcss-px-to-viewport-8-plugin";
import tailwindcss from "tailwindcss";
import autoprefixer from "autoprefixer";

// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
	const root = process.cwd();
	const env = loadEnv(mode, root);
	const {
		VITE_APP_BASE_URL,
		VITE_APP_PORT,
		VITE_APP_BUILD_GZIP,
		VITE_APP_OPEN,
		VITE_APP_AUTO_IMPORT,
		VITE_APP_COMPONENTS,
		VITE_APP_BUILD_BR,
		VITE_APP_API_URL_PROXY,
		VITE_APP_API_URL_PREFIX,
	} = env;

	const isBuild = command === "build";

	const vitePlugins = [vue(), vitePluginEslint()];

	if (VITE_APP_AUTO_IMPORT === "true") {
		vitePlugins.push(
			AutoImport({
				imports: [
					// 自动引入的api从这里找
					"vue",
					"vue-router",
					"pinia",
					{
						axios: [
							// default imports
							["default", "axios"], // import { default as axios } from 'axios',
						],
					},
				],
				eslintrc: {
					enabled: true, // 1、改为true用于生成eslint配置。2、生成后改回false，避免重复生成消耗
					filepath: "./.eslintrc-auto-import.json",
					globalsPropValue: true,
				},
				resolvers: [VantResolver()],
			}),
		);
	}
	if (VITE_APP_COMPONENTS === "true") {
		vitePlugins.push(
			Components({
				dirs: ["src/components"],
				resolvers: [VantResolver()],
			}),
		);
	}

	// vite-plugin-compression gzip compress
	if (VITE_APP_BUILD_GZIP === "true") {
		vitePlugins.push(
			viteCompression({
				verbose: false,
				disable: false,
				threshold: 10240,
				algorithm: "gzip",
				ext: ".gz",
			}),
		);
	}
	if (VITE_APP_BUILD_BR === "true") {
		vitePlugins.push(
			viteCompression({
				verbose: false,
				disable: false,
				threshold: 10240,
				algorithm: "brotliCompress",
				ext: ".br",
			}),
		);
	}

	// proxy
	const proxy = {};
	if (!isBuild) {
		// console.log("proxy", VITE_APP_API_URL_PROXY, VITE_APP_API_URL_PREFIX, VITE_APP_API_URL_PREFIX_1);
		// 不是生产环境
		if (VITE_APP_API_URL_PROXY && VITE_APP_API_URL_PREFIX !== "") {
			proxy[VITE_APP_API_URL_PREFIX] = {
				target: VITE_APP_API_URL_PROXY,
				rewrite: (path) => path.replace(VITE_APP_API_URL_PREFIX, VITE_APP_API_URL_PREFIX),
				changeOrigin: true,
			};
		}
	}
	return {
		root,
		base: VITE_APP_BASE_URL || "/",
		server: {
			host: "0.0.0.0",
			port: Number(VITE_APP_PORT || 3001),
			open: VITE_APP_OPEN === "true",
			cors: true,
			proxy,
		},
		plugins: vitePlugins,
		resolve: {
			alias: [
				{
					find: /^~/,
					replacement: `${resolve(__dirname, "./node_modules")}/`,
				},
				{
					find: /@\//,
					replacement: `${resolve(__dirname, "./src")}/`,
				},
			],
		},
		css: {
			// css预处理器
			postcss: {
				plugins: [
					tailwindcss,
					autoprefixer,
					pxToVw({
						unitToConvert: "px", // 需要转换的单位，默认为'px'
						viewportWidth: 375, // 视窗的宽度，对应的是我们设计稿的宽度，一般是750
						viewportHeight: 667, // 视窗的高度，根据750设备的宽度来指定，一般指定1334，也可以不配置
						unitPrecision: 5, // 指定`px`转换为视窗单位值的小数位数
						viewportUnit: "vw", // 指定需要转换成的视窗单位，建议使用vw
						fontViewportUnit: "vw", // 字体使用的视口单位
						selectorBlackList: [".ignore"], // 指定不转换为视窗单位的类，可以自定义，可以无限添加,建议定义一至两个通用的类名
						minPixelValue: 1, // 小于或等于`1px`不转换为视窗单位，你也可以设置为你想要的值
						mediaQuery: false, // 允许在媒体查询中转换`px`
						replace: true, // 是否直接更换属性值，而不添加备用属性
						exclude: [/node_modules/], // 设置忽略文件，用正则做目录名匹配
						landscape: true, // 是否处理横屏情况
					}),
				],
			},
			preprocessorOptions: {
				scss: {
					additionalData: '@import "@/assets/scss/index.scss";',
				},
			},
		},
		build: {
			sourcemap: true,
			rollupOptions: {
				output: {
					chunkFileNames: `static/js/[name]-[hash]-${new Date().getTime()}.js`,
					entryFileNames: `static/js/[name]-[hash]-${new Date().getTime()}.js`,
					assetFileNames: `static/[ext]/[name]-[hash]-${new Date().getTime()}.[ext]`,
					manualChunks: {
						vue: ["vue", "vue-router", "pinia"],
					},
				},
			},
			chunkSizeWarningLimit: 1500,
			minify: "terser",
			terserOptions: {
				compress: {
					/* drop_console: true,
					drop_debugger: true, */
				},
			},
		},
	};
});
